package com.guoguo.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.guoguo.base.BaseFilter;
import com.guoguo.base.StaticResource;
import com.guoguo.enums.UsersEnum;
import com.guoguo.utils.JsonUtils;
import com.guoguo.utils.RedisUtils;

/**
 * Created by Administrator on 2017/8/17 0017.
 */
public class UserTokenFilter extends BaseFilter {

    private Logger log = LoggerFactory.getLogger(UserTokenFilter.class);

    @Override
	public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 对请求中的token进行统一验证
     *
     * @param servletRequest
     * @param servletResponse
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        RedisUtils redisUtils = RedisUtils.getInstance();
        //当进行跨域预请求时，直接忽悠这个请求
        if (!"OPTIONS".equals(request.getMethod())) {
            //从请求中获取的token
            String token = request.getHeader("token");
            String appId = request.getHeader("appId");

            JSONObject jsonObject = null;
            //验证url是否是token例外
            if (urlFilterException(request.getRequestURI())) {
                log.debug("========================>>>>>>>>   validate url success!!!!!");
                chain.doFilter(request, response);
            } else {
                if (token != null && !"".equals(token)) {
                    //当token存在于缓存中，则token有效，否则无效
                    if (redisUtils.exists(StaticResource.SYS_TOKEN_KEY + token)) {
                        //从redis里获得token
                        String tokenUserName = redisUtils.getString(StaticResource.SYS_TOKEN_KEY + token);
                        //如果缓存里没有用户名等信息，则用户没有登录
                        if (tokenUserName == null && "".equals(tokenUserName)) {
                            jsonObject = JsonUtils.returnObject(UsersEnum.TOKEN_NULL_ERROR.getId(), "", UsersEnum.TOKEN_NULL_ERROR.getValue());
                            requestFailedSolution(Integer.valueOf(appId), jsonObject, response);
                        }
                        chain.doFilter(request, response);
                    } else {
                        //token验证失败
                        jsonObject = JsonUtils.returnObject(UsersEnum.TOKEN_ERROR.getId(), "", UsersEnum.TOKEN_ERROR.getValue());
                        requestFailedSolution(Integer.valueOf(appId), jsonObject, response);
                    }
                } else {
                    jsonObject = JsonUtils.returnObject(UsersEnum.TOKEN_NULL.getId(), "", UsersEnum.TOKEN_NULL.getValue());
                    requestFailedSolution(Integer.valueOf(appId), jsonObject, response);
                }
            }
        }
    }

    @Override
	public void destroy() {

    }

    /**
     * token验证时，不需要验证的url
     *
     * @param url
     * @return
     */
    private boolean urlFilterException(String url) {
        boolean flag = false;
        List<String> urlList = new ArrayList<>();
        urlList.add("/api/login");
        urlList.add("/api/category/getCategoryList");
        urlList.add("/api/category/getImages");
        urlList.add("/api/guestLogin");
        urlList.add("/api/register");
        urlList.add("/api/sendViliCode");
        urlList.add("/api/updateUserpwd");
        urlList.add("/api/invite/sharePage");

        log.debug("validate url ========================>>>>>>>>   " + url);
        for (String uri : urlList) {
            if (url.contains(uri)) {
                flag = true;
            }
        }
        return flag;
    }

//    private void requestFailedSolution(int appId, JSONObject jsonObject, HttpServletResponse response) throws IOException, ServletException {
//        if (appId == 0) {
//            response.sendRedirect("/main.html");
//        } else {
//            response.setHeader("Content-type", "text/html;charset=UTF-8");
//            response.setCharacterEncoding("UTF-8");
//            PrintWriter out = response.getWriter();
//            out.write(jsonObject.toJSONString());
//            out.flush();
//            out.close();
//        }
//    }

}
